<?php

namespace app\api\controller;

use app\admin\model\Ordderdistribution;
use app\admin\model\Order;
use app\common\controller\Api;
use think\Log;

class Stripe extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    CONST STRIPE_KEY = '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';
    //创建商品
    public function create_product(){
        $_key = self::STRIPE_KEY;
        $stripe = new \Stripe\StripeClient($_key);
        $arr =  $stripe->products->create([
            'name' => 'U962',
        ]);
        echo '<pre>';
        print_r($arr);
        $this->create_price($arr->id,9620117,1);
    }
//创建价格
    public function create_price($product_id,$order_id,$is_source){
        //获取订单对应的商品价格

        $_key = self::STRIPE_KEY;
        $stripe = new \Stripe\StripeClient($_key);
        $price_arr = $stripe->prices->create([
//            'unit_amount' => $goods_price*100,
            'unit_amount' => 2*100,
            'currency' => 'AUD',
            'tax_behavior' => 'exclusive',
            //'recurring' => ['interval' => 'day'],
            'product' => $product_id,
        ]);
        //print_r($price_arr->id);die;
        $this->actionStripe($price_arr->id,$order_id,$is_source);
    }
    /**
     * 创建stripe支付
     */
    public function actionStripe($price_id,$order_id,$is_source)
    {
        $_key = self::STRIPE_KEY;

        $domain = $this->request->domain();

        //如果是AI订阅和AI作品打样的话
        $cancel_url = 'https://a962.hzybh.com/web/#/';
        $success_url = 'https://a962.hzybh.com/web/#/';
        // stripe 生成订单

        \Stripe\Stripe::setApiKey($_key);
        $checkout_session = \Stripe\Checkout\Session::create([
            'line_items' => [
                [
                'price' => $price_id, // 产品id
                'quantity' => 1,
                ]
            ],
            'mode' => 'payment',
            'success_url' => $success_url,
            'cancel_url' => $cancel_url,
            'locale'=>'en', # 设置页面为英文
            'automatic_tax' => [
                'enabled' => true,
            ],
            'metadata' => [
                'order_id' => $order_id,
            ],
        ]);
        echo '<pre>';
        print_r($checkout_session);
        print_r($checkout_session->url);
        exit;
        header("HTTP/1.1 303 See Other");
        header("Location: " . $checkout_session->url);
    }

    /**
     * @return bool|void
     * {
    "id": "evt_1OZStdAYRiLGlQ0KqntarmsY",
    "object": "event",
    "api_version": "2023-10-16",
    "created": 1705474004,
    "data": {
    "object": {
    "id": "cs_live_a18wA2pXpbduQ4GzCJ8Cd4yDHKdVm9hPlpr5qmgJDxrPPKj65D80KGFYjD",
    "object": "checkout.session",
    "after_expiration": null,
    "allow_promotion_codes": null,
    "amount_subtotal": 200,
    "amount_total": 200,
    "automatic_tax": {
    "enabled": true,
    "status": "complete"
    },
    "billing_address_collection": null,
    "cancel_url": "https://a962.hzybh.com/web/#/",
    "client_reference_id": null,
    "client_secret": null,
    "consent": null,
    "consent_collection": null,
    "created": 1705472648,
    "currency": "aud",
    "currency_conversion": null,
    "custom_fields": [

    ],
    "custom_text": {
    "after_submit": null,
    "shipping_address": null,
    "submit": null,
    "terms_of_service_acceptance": null
    },
    "customer": null,
    "customer_creation": "if_required",
    "customer_details": {
    "address": {
    "city": null,
    "country": "AU",
    "line1": null,
    "line2": null,
    "postal_code": null,
    "state": null
    },
    "email": "154e420970@qq.com",
    "name": "Ruiqi Yang",
    "phone": null,
    "tax_exempt": "none",
    "tax_ids": [

    ]
    },
    "customer_email": null,
    "expires_at": 1705559048,
    "invoice": null,
    "invoice_creation": {
    "enabled": false,
    "invoice_data": {
    "account_tax_ids": null,
    "custom_fields": null,
    "description": null,
    "footer": null,
    "metadata": {
    },
    "rendering_options": null
    }
    },
    "livemode": true,
    "locale": null,
    "metadata": {
    "order_id": "9620117"
    },
    "mode": "payment",
    "payment_intent": "pi_3OZStYAYRiLGlQ0K0wjqjb9V",
    "payment_link": null,
    "payment_method_collection": "if_required",
    "payment_method_configuration_details": {
    "id": "pmc_1OZS6uAYRiLGlQ0K9MxU0Tb6",
    "parent": null
    },
    "payment_method_options": {
    },
    "payment_method_types": [
    "card",
    "link"
    ],
    "payment_status": "paid",
    "phone_number_collection": {
    "enabled": false
    },
    "recovered_from": null,
    "setup_intent": null,
    "shipping_address_collection": null,
    "shipping_cost": null,
    "shipping_details": null,
    "shipping_options": [

    ],
    "status": "complete",
    "submit_type": null,
    "subscription": null,
    "success_url": "https://a962.hzybh.com/web/#/",
    "total_details": {
    "amount_discount": 0,
    "amount_shipping": 0,
    "amount_tax": 0
    },
    "ui_mode": "hosted",
    "url": null
    }
    },
    "livemode": true,
    "pending_webhooks": 1,
    "request": {
    "id": null,
    "idempotency_key": null
    },
    "type": "checkout.session.completed"
    }
     */
    public function actionNotify()
    {
        Log::record('支付进来了', 'info');
        $_key = self::STRIPE_KEY;
        \Stripe\Stripe::setApiKey($_key);
        $payload = file_get_contents('php://input');
        Log::error("支付结果回调");
        Log::error($payload);
        $event = null;
        try {
            $event = \Stripe\Event::constructFrom(
                json_decode($payload, true)
            );
        } catch(\UnexpectedValueException $e) {
            // Invalid payload
            http_response_code(400);
            exit();
        }
        // Handle the event
        Log::record('event12333333' . var_export($event->type, true), 'info');
        switch ($event->type) {
            case 'checkout.session.completed':
                $succeeded = $event->data->object;
                $content = "=========".date('Y-m-d H:i:s',time())."==========\r\n";
                $content .= json_encode($succeeded);
                \think\Log::record('content=======' . var_export($content, true), 'info');
                $token = input('token', '');
                if ($succeeded->status == 'complete') {
                    $order_id = $succeeded->metadata->order_id;
                    $type = $succeeded->metadata->type;
                    if ($type==1){
                        $order = Order::where('id', $order_id)->find();
                    }else{
                        $order = Ordderdistribution::where('id', $order_id)->find();
                    }
                    if (!$order) {
                        Log::record('order is null', 'info');
                        return false;
                    }
                    if ($order->pay_status == 1) {
                        $order->pay_status = 2;
                        $order->pay_time = time();
                        $order->save();
                    }
                }
                break;
            case 'checkout.session.async_payment_failed':
                \think\Log::record('pay is failed', 'info');
                break;
            default:
                echo 'Received unknown event type ' . $event->type;
                break;
        }
        Log::record('done', 'info');
        return true;
    }

}